<template>
  <li 
    :class="[
      'bx-anchor-link',
      {
        'bx-anchor-link--active': isActive
      }
    ]"
  >
    <a 
      :href="href"
      :class="'bx-anchor-link__title'"
      @click="handleClick"
    >
      <slot>{{ title }}</slot>
    </a>
    <ul v-if="$slots.default" class="bx-anchor-link__children">
      <slot></slot>
    </ul>
  </li>
</template>

<script>
import { inject, computed, onMounted, onUnmounted } from 'vue'

export default {
  name: 'BxAnchorLink',
  props: {
    href: {
      type: String,
      required: true
    },
    title: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const anchorContext = inject('anchorContext', null)

    const isActive = computed(() => {
      return anchorContext && anchorContext.activeLink.value === props.href
    })

    const handleClick = (e) => {
      e.preventDefault()
      const targetElement = document.querySelector(props.href)
      if (targetElement && anchorContext) {
        const container = anchorContext.getContainer()
        const offset = anchorContext.offset
        const targetScrollTop = targetElement.offsetTop - offset

        if (container === window) {
          window.scrollTo({ top: targetScrollTop, behavior: 'smooth' })
        } else {
          container.scrollTo({ top: targetScrollTop, behavior: 'smooth' })
        }
      }
    }

    onMounted(() => {
      if (anchorContext) {
        anchorContext.registerLink({ href: props.href, title: props.title })
      }
    })

    onUnmounted(() => {
      if (anchorContext) {
        anchorContext.unregisterLink({ href: props.href, title: props.title })
      }
    })

    return {
      isActive,
      handleClick
    }
  }
}
</script>

<style scoped>
.bx-anchor-link {
  padding: 4px 0;
}

.bx-anchor-link__title {
  display: block;
  padding: 4px 8px;
  color: var(--bx-text-secondary);
  text-decoration: none;
  transition: all 0.2s ease;
  border-radius: var(--bx-radius-small);
}

.bx-anchor-link__title:hover {
  background: var(--bx-glass-bg-hover);
  color: var(--bx-text-primary);
}

.bx-anchor-link--active .bx-anchor-link__title {
  color: rgba(0, 122, 255, 0.8);
  font-weight: 600;
  background: rgba(0, 122, 255, 0.1);
}

.bx-anchor-link__children {
  list-style: none;
  padding-left: 16px;
  margin: 0;
}
</style>

